package com.atguigu.tingshu.payment.service.impl;

import cn.hutool.core.lang.Assert;
import com.atguigu.tingshu.account.AccountFeignClient;
import com.atguigu.tingshu.common.constant.SystemConstant;
import com.atguigu.tingshu.common.execption.GuiguException;
import com.atguigu.tingshu.common.result.Result;
import com.atguigu.tingshu.common.result.ResultCodeEnum;
import com.atguigu.tingshu.common.util.AuthContextHolder;
import com.atguigu.tingshu.model.account.RechargeInfo;
import com.atguigu.tingshu.model.order.OrderInfo;
import com.atguigu.tingshu.model.payment.PaymentInfo;
import com.atguigu.tingshu.order.client.OrderFeignClient;
import com.atguigu.tingshu.payment.mapper.PaymentInfoMapper;
import com.atguigu.tingshu.payment.service.PaymentInfoService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wechat.pay.java.service.payments.model.Transaction;
import io.seata.core.context.RootContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

@Slf4j
@Service
@SuppressWarnings({"all"})
public class PaymentInfoServiceImpl extends ServiceImpl<PaymentInfoMapper, PaymentInfo> implements PaymentInfoService {


    @Autowired
    private OrderFeignClient orderFeignClient;

    @Autowired
    private AccountFeignClient accountFeignClient;

    /**
     * 保存本地交易记录
     *
     * @param paymentType:支付类型 1301-订单 1302-充值
     * @param orderNo:         订单编号
     * @return
     */
    @Override
    public PaymentInfo savePaymentInfo(String paymentType, String orderNo) {
        //0.根据订单/充值编号查询交易记录 存在直接返回，不存在新增
        LambdaQueryWrapper<PaymentInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(PaymentInfo::getOrderNo, orderNo);
        PaymentInfo paymentInfo = this.getOne(queryWrapper);
        if (paymentInfo != null) {
            return paymentInfo;
        } else {
            //1.构建本地交易记录对象
            paymentInfo = new PaymentInfo();

            //1.1 封装对象中简单属性
            Long userId = AuthContextHolder.getUserId();
            paymentInfo.setUserId(userId);
            paymentInfo.setPaymentType(paymentType);
            paymentInfo.setOrderNo(orderNo);
            paymentInfo.setPayWay(SystemConstant.ORDER_PAY_WAY_WEIXIN);
            paymentInfo.setPaymentStatus(SystemConstant.PAYMENT_STATUS_UNPAID);
            //1.2 封装本地交易记录中金额跟内容-远程调用其他服务获取
            //1.3 判断支付类型：订单
            if (SystemConstant.PAYMENT_TYPE_ORDER.equals(paymentType)) {
                //1.3.1 远程调用订单服务获取订单信息
                OrderInfo orderInfo = orderFeignClient.getOrderInfo(orderNo).getData();
                Assert.notNull(orderInfo, "订单不存在");
                //1.3.2 校验订单状态是否为：未支付
                boolean flag = SystemConstant.ORDER_STATUS_UNPAID.equals(orderInfo.getOrderStatus());
                Assert.state(flag, "订单状态有误！");
                //1.3.3 封装本地交易记录中交易内容跟金额
                paymentInfo.setAmount(orderInfo.getOrderAmount());
                paymentInfo.setContent(orderInfo.getOrderTitle());
            } else if (SystemConstant.PAYMENT_TYPE_RECHARGE.equals(paymentType)) {
                //1.4 判断支付类型：充值
                //1.4.1 远程调用账户服务获取充值信息
                RechargeInfo rechargeInfo = accountFeignClient.getRechargeInfo(orderNo).getData();
                Assert.notNull(rechargeInfo, "充值记录不存在");
                //1.4.2 校验充值状态是否为：未支付
                boolean flag = SystemConstant.ORDER_STATUS_UNPAID.equals(rechargeInfo.getRechargeStatus());
                Assert.state(flag, "充值状态有误！");
                //1.4.3 封装本地交易记录中交易内容跟金额
                paymentInfo.setAmount(rechargeInfo.getRechargeAmount());
                paymentInfo.setContent("用户充值：" + rechargeInfo.getRechargeAmount());
            }
            //2.保存本地交易记录对象
            this.save(paymentInfo);
        }
        return paymentInfo;
    }


    /**
     * 处理用户付款成功后两条业务分之后续业务完善（1.订单 2.充值）
     *
     * @param transaction 微信支付交易对象
     */
    @Override
    public void updatePaymentInfo(Transaction transaction) {
        //1.判断并修改本地交易记录状态：已支付 及更新回调信息
        //1.1 查询本地交易记录状态 判断是否为未支付
        String orderNo = transaction.getOutTradeNo();
        LambdaQueryWrapper<PaymentInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(PaymentInfo::getOrderNo, orderNo);
        PaymentInfo paymentInfo = this.getOne(queryWrapper);
        if (SystemConstant.PAYMENT_STATUS_UNPAID.equals(paymentInfo.getPaymentStatus())) {
            //1.2 更新支付状态、回调时间及内容、微信端交易号
            String transactionId = transaction.getTransactionId();
            paymentInfo.setOutTradeNo(transactionId);
            paymentInfo.setCallbackTime(new Date());
            paymentInfo.setCallbackContent(transaction.toString());
            paymentInfo.setPaymentStatus(SystemConstant.PAYMENT_STATUS_PAID);
            this.updateById(paymentInfo);

            //2.处理交易类型为：订单 业务线
            String paymentType = paymentInfo.getPaymentType();
            if (SystemConstant.PAYMENT_TYPE_ORDER.equals(paymentType)) {
                //2.1 远程调用订单服务修改订单支付状态包含虚拟物品发货
                Result result = orderFeignClient.orderPaySuccess(orderNo);
                if (!ResultCodeEnum.SUCCESS.getCode().equals(result.getCode())) {
                    throw new GuiguException(500, "修改订单状态异常");
                }

            } else if (SystemConstant.PAYMENT_TYPE_RECHARGE.equals(paymentType)) {
                //3.处理交易类型为：充值 业务线
                //3.1 远程调用账户服务完成充值业务
                Result result = accountFeignClient.rechargePaySuccess(orderNo);
                if (!ResultCodeEnum.SUCCESS.getCode().equals(result.getCode())) {
                    throw new GuiguException(500, "充值异常");
                }

            }
        }
    }
}
